<script setup lang='tsx'>
import { ProFormOption, ProTableOption, ProTableRef } from 'tdesign-pro-component';
import { USER_ENABLED_STATUS } from '@/common/const';
import { createSystemUser, getSystemUser, getSystemUserPage, updateSystemUser, deleteSystemUser } from '@/api/user';
import { filterByValue } from '@/utils';
import { DropdownOption, MessagePlugin } from 'tdesign-vue-next';
import { onMounted, ref } from 'vue';
import { getRoleList } from '@/api/role';
import { getRoleIdsByUserId, saveUserRole } from '@/api/user';
import {CHECKED_PROPS, UNCHECKED_PROPS} from '@/common/const';

const visible = ref(false);

const currentId = ref<NullAble<number>>(null);

const proTableRef = ref<NullAble<ProTableRef>>(null);

const roleList = ref<LabelOptionList>([]);

const roleIds = ref<number[]>([]);

const loading = ref(false);

const chooseRoleVisible = ref(false);

const options: ProTableOption[] = [
    {
        key: 'id',
        title: '序号',
        hideInSearch: true
    },
    {
        key: 'username',
        title: '用户名',
        isSlot: true
    },
    {
        key: 'enabled',
        title: '封禁状态',
        type: 'radio',
        data: USER_ENABLED_STATUS,
        isSlot: true,
        render: ({ row }) => <div>{filterByValue(USER_ENABLED_STATUS, row.enabled)}</div>
    },
    {
        key: 'createTime',
        title: '注册时间',
        hideInSearch: true
    },
    {
        key: 'actions',
        title: '操作',
        hideInSearch: true,
        isSlot: true,
    }
];

const userFormOption = ref<ProFormOption[]>([
    {
        name: 'username',
        label: '用户名',
        rules: [
            { required: true, message: '请输入用户名' },
        ]
    },
    {
        name: 'password',
        label: '密码',
        textProps: {
            type: 'password'
        },
        rules: [
            { required: true, message: '请输入密码' },
        ]
    }
]);

onMounted(() => {
    getRoleList({}).then(res => {
        roleList.value = res.map(item => ({ label: item.nameZh, value: item.id }));
    })
})

async function request(data: any) {
    return await getSystemUserPage(data);
}

const moreOption: DropdownOption[] = [
    {
        content: '配置权限',
        value: 1
    },
    {
        content: '封禁/启用',
        value: 2
    }
]

function handleSubmit(data: any) {
    const fn = currentId.value === null ? createSystemUser : updateSystemUser;
    const params = {
        ...data,
        id: currentId.value
    }
    if (currentId.value === null) {
        delete params.id
    }

    fn(params).then(() => {
        visible.value = false;
        proTableRef.value?.reset();
    })
}

async function formRequest() {
    loading.value = true;
    if (currentId.value === null) {
        return null
    } else {
        loading.value = false;
        return getSystemUser(currentId.value!)
    }
}
function handleShow(id: NullAble<number>) {
    currentId.value = id;
    if (id === null) {
        userFormOption.value[1].rules = [
            { required: true, message: '请输入密码' },
        ];
        userFormOption.value[1].formItemProps = {};
    } else {
        userFormOption.value[1].formItemProps = { tips: '如果修改时不填写，则不修改密码。' };
        userFormOption.value[1].rules = undefined;
    }
    visible.value = true;
}

function handleConfirm(row: any) {
    deleteSystemUser(row.id).then(() => {
        proTableRef.value?.reset();
    })
}

function handleDropdownClick(option: DropdownOption, userId: number) {
    currentId.value = userId;
    if (option.value === 1) {
        getRoleIdsByUserId(userId).then(res => {
            roleIds.value = res;
            chooseRoleVisible.value = true;
        });
    }
}

function handleUserRoleConfirm() {
    saveUserRole({
        userId: currentId.value!,
        roleIds: roleIds.value
    }).then(() => {
        resetChooseUserRole();
        MessagePlugin.success('保存成功');
    })
}

function handleUserRoleClose() {
    resetChooseUserRole();
}

function resetChooseUserRole() {
    chooseRoleVisible.value = false;
    currentId.value = null;
    roleIds.value = [];
}
</script>

<template>
    <div>
        <ModalForm width="600" :request="formRequest" header="创建用户" v-model:visible="visible" :options="userFormOption"
            @submit="handleSubmit" />
        <ProTable ref="proTableRef" :request :options>
            <template #pro-table-title>
                <div>
                    用户列表
                </div>
            </template>

            <template #pro-table-actions>
                <div>
                    <t-button @click="handleShow(null)">创建用户</t-button>
                </div>
            </template>

            <template #table-username="{ row }">
                <t-link hover="color" theme="primary">{{ row.username }}</t-link>
            </template>

            <template #table-actions="{ row }">
                <div>
                    <t-link theme="primary" @click="handleShow(row.id)" hover="color"
                        style="margin-right: 8px;">编辑</t-link>
                    <ProButton @confirm="handleConfirm(row)" :confirmBtn="{ theme: 'danger' }" theme="link">
                        删除
                        <template #content>
                            你正在执行删除操作，确认是否删除【{{ row.username }}】账户？
                        </template>
                        <template #title>
                            系统提示
                        </template>
                    </ProButton>
                    <DropdownButton @click="(option: DropdownOption) => handleDropdownClick(option, row.id)" :options="moreOption" />
                </div>
            </template>
        </ProTable>

        <t-dialog @confirm="handleUserRoleConfirm" @close="handleUserRoleClose" header="配置权限" v-model:visible="chooseRoleVisible">
            <div>
                <t-check-tag-group v-model="roleIds" :options="roleList as any" multiple :checked-props="CHECKED_PROPS"  :unchecked-props="UNCHECKED_PROPS"/>
            </div>
        </t-dialog>
    </div>
</template>

<style lang='scss'></style>